<template>
  <div>
    <a-row type="flex" align="middle" v-show="!isEdit" style="padding-bottom: 20px">
      <a-col>
        <commodity-selection
          v-model="result.selectedCommodityId"
          :commodity="result.selectedCommodity"
          @change="handleCommoditySelected"
        />
      </a-col>
      <a-col offset="1" v-if="Object.keys(result.selectedCommodity).length > 0">
        已选: {{ result.selectedCommodity.name }}
      </a-col>
    </a-row>

    <a-row>
      <div v-if="Object.keys(result.selectedCommodity).length > 0">
        <sku-table
          v-model="result.sku"
          :is-edit="isEdit"
          :extra-columns="skuSpecificationInformationColumns"
          :multiple-specification="multipleSpecification"
          :multiple-specification-detail="skuSpecificationDetail"
          @change="handleSkuTableChange"
        />
      </div>
    </a-row>
  </div>
</template>

<script>
  import CommoditySelection from '@/components/CommoditySelection/CommoditySelection'
  import SkuTable from '@/components/SkuTable/SkuTable'
  import cloneDeep from 'lodash.clonedeep'
  import Vue from 'vue'
  import pick from 'lodash.pick'

  export default {
    name: 'CommodityActivitySku',
    components: { SkuTable, CommoditySelection },
    props: {
      value: {
        type: Object,
        default: () => {
          return {
            selectedCommodityId: [],
            selectedCommodity: {},
            sku: []
          }
        }
      }
    },
    watch: {
      value: {
        handler: function (obj) {
          if (obj.hasOwnProperty('isEdit') && obj.isEdit) {
            this.isEdit = true
            Vue.delete(obj, 'isEdit')
            this.editDefaultResult = cloneDeep(obj) // 之前选中的商品数据,这里分开赋值,不然会和 result 搞乱
          }
          this.result = cloneDeep(obj) // 要给 result 赋值,这样才能传递给 CommoditySelection 组件并返回选中的商品数据
        }
      }
    },
    data () {
      return {
        skuSpecificationInformationColumns: [
          { title: '入仓价', scopedSlots: { customRender: 'entry_price' }, editable: false },
          { title: '进价', scopedSlots: { customRender: 'purchase_price' }, editable: false },
          { title: '大咖价', scopedSlots: { customRender: 'strongman_price' } },
          { title: '精英价', scopedSlots: { customRender: 'elite_price' } },
          { title: '群主价', scopedSlots: { customRender: 'group_owner_price' } },
          { title: '对外指导价', scopedSlots: { customRender: 'external_guide_price' } },
          { title: '直接邀请', scopedSlots: { customRender: 'direct_invitation' } },
          { title: '间接邀请', scopedSlots: { customRender: 'indirect_invitation' } },
          { title: '库存', scopedSlots: { customRender: 'stock' } },
          // { title: '预计销量', scopedSlots: { customRender: 'estimated_sales' } }, // 已废弃
          { title: 'sku_id', scopedSlots: { customRender: 'sku_id' }, hidden: true },
          { title: 'sku_picture', scopedSlots: { customRender: 'sku_picture' }, hidden: true }
        ],
        multipleSpecification: {},
        skuSpecificationDetail: {},

        result: this.value,
        editDefaultResult: {},
        isEdit: false,
        isInitialed: false
      }
    },
    methods: {
      handleCommoditySelected (value) {
        if (this.result.selectedCommodity['id'] !== value[0]['id']) {
          // 通知商品变更
          this.$emit('commodityChanged', value[0])
        }

        this.result.selectedCommodity = {} // 这里置空一下,(根据上面 v-if 的条件) 刷新 sku-table 组件,不然 sku-table 内部处理老数据有问题

        this.$nextTick(_ => {
          this.result.selectedCommodity = value[0]
          this.result.selectedCommodityId = [value[0]['id']]

          // 如果是编辑的情况, 编辑原来的活动 SKU
          // 商品的 SKU 规格
          this.multipleSpecification = {} // 这里得初始化下, 因为 vue.set 之前的 key 还在
          this.skuSpecificationDetail = {}
          const attributes = this.isEdit ? this.editDefaultResult.selectedCommodity.attributes : this.result.selectedCommodity.attributes

          attributes.forEach(item => {
            Vue.set(this.multipleSpecification, item.id, item.name) // 规格
            Vue.set(this.skuSpecificationDetail, item.id, item.values.map(value => value.content))
          })

          // 商品的 SKU 值
          this.result.sku = []
          const skus = this.isEdit ? this.editDefaultResult.sku : this.result.selectedCommodity.skus
          skus.forEach((item, index) => {
            var temp = {}
            // 自定义规格数据
            item.values.forEach(item => {
              temp[item.attribute_id] = item.content
            })
            Vue.set(this.result.sku, index, Object.assign(
              temp,
              {
                'strongman_price': item.strongman_price / 100 || 0,
                'elite_price': item.elite_price / 100 || 0,
                'group_owner_price': item.group_owner_price / 100 || 0,
                'external_guide_price': item.external_guide_price / 100 || 0,
                'direct_invitation': item.direct_invitation / 100 || 0,
                'indirect_invitation': item.indirect_invitation / 100 || 0,
                'stock': item.stock || 0,
                // 'estimated_sales': item.estimated_sales || 0, // 已废弃
                'sku_picture': (item.attachments && item.attachments.map(att => pick(att, ['id', 'url']))) || [],

                'entry_price': this.isEdit ? (item.entry_price / 100 || 0) : (item.entry_price || 0),
                'purchase_price': this.isEdit ? (item.purchase_price / 100 || 0) : (item.purchase_price || 0),
                'sku_id': item.id || null
              }
            ))
          })

          this.$emit('change', this.result)
        })
      },
      handleSkuTableChange (value) {
        this.$emit('change', this.result)
      }
    }
  }
</script>

<style scoped>

</style>
